package cn.js.ccit.flowersmall.user.service.impl;

import cn.js.ccit.flowersmall.user.entity.PermissionEntity;
import cn.js.ccit.flowersmall.user.entity.UserEntity;
import cn.js.ccit.flowersmall.user.mapper.PermissionMapper;
import cn.js.ccit.flowersmall.user.mapper.UserMapper;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

// 实现用户详情服务接口
@Service
@Primary
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity user = userMapper.findByUsername(username);
        if(user == null) {
            return null;
        }

        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
       // 调用 mapper，根据 user ID 获取权限列表
        List<PermissionEntity> permissionList = permissionMapper.findPermisByUserId(user.getId());

        // 遍历权限列表，构建授权对象，放入授权对象列表
        permissionList.forEach(tbPermission -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
            grantedAuthorityList.add(grantedAuthority);
        });
//        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("USER");
//        grantedAuthorityList.add(grantedAuthority);

        return new User(user.getUsername(), user.getPassword(), grantedAuthorityList);
    }
}